const KEYMAP = {
    token: "token",
    userId: 'userId',
    userName: 'userName',
};
const webStorage = window.sessionStorage;

class LoginInfo {
    constructor() {
        this.info = {
            token: '',
            userId: '',
            userName: '',
        };
    }

    static getInstance = () => {
        if(window.loginInfo){
            return window.loginInfo;
        }else{
            window.loginInfo = new LoginInfo();
            return window.loginInfo;
        }
    };

    get token(){
        if(this.info.token){
            return this.info.token;
        }else {
            this.info.token = webStorage.getItem(KEYMAP.token) || '';
            return this.info.token;
        }
    }
    set token(token){
        this.info.token = token;
        webStorage.setItem(KEYMAP.token, token);
    }

    get userId(){
        if(this.info.userId){
            return this.info.userId;
        }else {
            this.info.userId = localStorage.getItem(KEYMAP.userId) || '';
            return this.info.userId;
        }
    }
    set userId(userId){
        this.info.userId = userId;
        webStorage.setItem(KEYMAP.userId, userId);
        localStorage.setItem(KEYMAP.userId, userId);
    }

    get userName(){
        if(this.info.userName){
            return this.info.userName;
        }else {
            this.info.userName = localStorage.getItem(KEYMAP.userName) || '';
            return this.info.userName;
        }
    }
    set userName(userName){
        this.info.userName = userName;
        webStorage.setItem(KEYMAP.userName, userName);
        localStorage.setItem(KEYMAP.userName, userName);
    }

    clearInfo = (clearAll) => {
        for(let key in KEYMAP){
            if(clearAll){
                // @ts-ignore
                this.info[KEYMAP[key]] = '';
                // @ts-ignore
                webStorage.removeItem(KEYMAP[key]);
                // @ts-ignore
                localStorage.removeItem(KEYMAP[key]);
            }else{
                if(!(this.autoLogin || (key === KEYMAP.loginId || key === KEYMAP.pwd || key === KEYMAP.autoLogin))){
                    // @ts-ignore
                    this.info[KEYMAP[key]] = '';
                    // @ts-ignore
                    webStorage.removeItem(KEYMAP[key]);
                    // @ts-ignore
                    localStorage.removeItem(KEYMAP[key]);
                }
            }
        }
    }
}

export default LoginInfo;
